<!-- 新增/编辑 对话框 -->

<template>

  <el-dialog
      :model-value="dialogVisible"
      :title="dialogTitle"
      width="30%"
      @close="handleClose"
  >
    <!--  对话框中的内容  -->
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
    >


      <el-form-item label="上级菜单" prop="parentId">
        <el-select v-model="form.parentId" placeholder="请选择上级菜单">
          <template v-for="item in tableData">
            <el-option :label="item.name" :value="item.id"></el-option>
            <template v-for="child in item.children">
              <el-option :label="child.name" :value="child.id">
                <span>{{ " -- " + child.name }}</span>
              </el-option>
            </template>
          </template>
        </el-select>
      </el-form-item>

      <el-form-item label="菜单类型" prop="menuType" label-width="100px">
        <el-radio-group v-model="form.menuType">
          <el-radio :label="'M'">目录</el-radio>
          <el-radio :label="'C'">菜单</el-radio>
          <el-radio :label="'F'">按钮</el-radio>
        </el-radio-group>
      </el-form-item>


      <el-form-item label="菜单图标" prop="icon">
        <el-input v-model="form.icon" />
      </el-form-item>
      <el-form-item label="菜单名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="权限标识" prop="perms">
        <el-input v-model="form.perms" />
      </el-form-item>
      <el-form-item label="组件路径" prop="component">
        <el-input v-model="form.component" />
      </el-form-item>
      <el-form-item label="显示顺序" prop="orderNum" >
        <el-input-number v-model="form.orderNum" :min="1" label="显示顺序"></el-input-number>
      </el-form-item>


    </el-form>

    <template #footer>
      <span class="dialog-footer">
<el-button type="primary" @click="handleConfirm">确认</el-button>
<el-button @click="handleClose"
>取消</el-button
>
</span>
    </template>
  </el-dialog>
</template>
<script setup>
import {defineEmits, defineProps,ref,watch } from "vue"
import requestUtil,{getBaseUrl} from "@/util/request";
import { ElMessage } from 'element-plus'

// 接收父页面传递的值
const props=defineProps(
    {
      id:{
        type:Number,
        default:-1,
        required:true
      },
      dialogTitle:{
        type:String,
        default:'',
        required:true
      },
      dialogVisible:{
        type:Boolean,
        default:false,
        required:true
      },
      // 父页面必须传来tableData作为上级菜单
      tableData:{
        type:Array,
        default:[],
        required:true
      }
    }
)


const form=ref({
  id:-1,
  username:"",
  password:"123456",
  status:"0",
  phonenumber:"",
  email:"",
  remark:""
})

// 调用后端接口，检查用户名是否存在
const checkUsername = async (rule, value, callback) => {
  if(form.value.id==-1){
    const res=await requestUtil.post("sys/user/checkUserName",
        {username:form.value.username});
    if (res.code == -1) {
      callback(new Error(res.msg));
    } else {
      callback();
    }
  }else{
    callback();
  }
}
const rules=ref({
  username:[
    { required: true, message: '请输入用户名'},
    { required: true, validator: checkUsername, trigger: "blur" }
  ],
  email: [{ required: true, message: "邮箱地址不能为空", trigger: "blur" }, { type:
        "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }],
  phonenumber: [{ required: true, message: "手机号码不能为空", trigger: "blur" }, {
    pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger:
        "blur" }],
})

const formRef=ref(null)

const initFormData=async(id)=>{
  const res=await requestUtil.get("sys/user/"+id);
  console.log(res.data)
  form.value=res.data;
}

// 监视模态框的变化
watch(
    ()=>props.dialogVisible,
    ()=>{
      let id=props.id;
      console.log("id="+id)
      if(id!=-1){
        initFormData(id);  // 这是用户修改操作时，就给模态框中变量赋值，值的来源需要调用后端接口返回，相当于回显。
      }else{
        form.value={       // 这是新增用户时，就给他初始化
          id:-1,
          username:"",
          password:"123456",
          status:"0",
          phonenumber:"",
          email:"",
          remark:""
        }
      }
    }
)
const emits=defineEmits(['update:modelValue','initTableData'])

const handleClose=()=>{
  emits('update:modelValue',false)
}

// 点击确认时，保存用户数据（新增/修改后的）
const handleConfirm=()=>{
  formRef.value.validate(async(valid)=>{
    if(valid){
      let result=await requestUtil.post("sys/user/save",form.value);
      if(result.code=== '0'){
        ElMessage.success("执行成功！")
        formRef.value.resetFields();
        emits("initTableData")
        handleClose();
      }else{
        ElMessage.error(result.msg);
      }
    }else{
      console.log("fail")
    }
  })
}
</script>
<style lang="scss" scoped>
</style>